package com.jin10.listener;

import com.jin10.annotation.TitleType;
import com.jin10.constant.TitleHandlerClassMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.context.event.ApplicationStartedEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/**
 * @author raofy
 * @date 2022-02-09 16:43
 * @desc 扫描注入不同文章类型的处理类
 */
@Component
public class TitleTypeHandlerClassInjection implements ApplicationListener<ApplicationStartedEvent> {
    private static final Logger log = LoggerFactory.getLogger(TitleTypeHandlerClassInjection.class);


    @Override
    public void onApplicationEvent(ApplicationStartedEvent event) {
        // 自定义bean容器
        Map<Integer, Object> map = new HashMap<>();
        Map<String, Object> titleHandlerBeansMap = event.getApplicationContext().getBeansWithAnnotation(TitleType.class);
        for (Map.Entry<String, Object> entry : titleHandlerBeansMap.entrySet()) {
            Object object = entry.getValue();
            TitleType annotation = AnnotationUtils.findAnnotation(object.getClass(), TitleType.class);
            if (annotation != null) {
                map.put(annotation.value(), object);
            }
        }
        TitleHandlerClassMap titleHandlerClassMap = (TitleHandlerClassMap) event.getApplicationContext().getBean("titleHandlerClassMap");
        titleHandlerClassMap.setBeanTable(map);
    }
}
